#include "StdAfx.h"
#include "GoogleAuth.h"

namespace GoogleProtocol
{

CGoogleAuth::CGoogleAuth()
{
}

CGoogleAuth::~CGoogleAuth(void)
{
}

BOOL CGoogleAuth::AnalyzerStream(CGoogleStream* stream)
{
	LPVOID outBuf = NULL;
	DWORD nBufSize;
	BOOL bResult;

	if (stream == NULL)
	{
		_ASSERT(FALSE);
		return FALSE;
	}

	outBuf = stream->GetStream();
	nBufSize = stream->GetSize();

	if (outBuf == NULL || nBufSize == 0)
		return FALSE;

	bResult = Parse((const char *)outBuf);

	return bResult;
}

BOOL CGoogleAuth::AnalyzerBuffer(const wchar_t* pAuthBuffer)
{
	_ASSERT(pAuthBuffer != NULL);

	int len = wcslen(pAuthBuffer) * 2;
	char* pBufA = new char[len + 1];
	if (pBufA == NULL)
		return FALSE;

	wcstombs(pBufA, pAuthBuffer, len);
	BOOL bResult;

	bResult = Parse(pBufA);

	return bResult;
}

CGoogleAuth& CGoogleAuth::operator= (CGoogleAuth * pAuth)
{
	this->m_strAuth = pAuth->m_strAuth;
	this->m_strLSID = pAuth->m_strLSID;
	this->m_strSID  = pAuth->m_strSID;
	return *this;
}

BOOL CGoogleAuth::Parse(const char* lpData)
{
	if (lpData == NULL)
	{
		_ASSERT(FALSE);
		return FALSE;
	}

	LPSTR lpStream = strdup(lpData);
	char seps[] = "\n";
	char* token;

	char* SID  = "SID";
	char* LSID = "LSID";
	char* Auth = "Auth";

	token = strtok(lpStream, seps);
	while (token != NULL)
	{
		if (memcmp(token, SID, strlen(SID)) == 0)
		{
			char* psid = token + strlen(SID) + 1;
			if (psid != NULL)
				m_strSID = psid;
		}

		if (memcmp(token, LSID, strlen(LSID)) == 0)
		{
			char* plsid = token + strlen(LSID) + 1;
			if (plsid != NULL)
				m_strLSID = plsid;
		}

		if (memcmp(token, Auth, strlen(Auth)) == 0)
		{
			char* pauth = token + strlen(Auth) + 1;
			if (pauth != NULL)
				m_strAuth = pauth;
		}

		token = strtok(NULL, seps);
	}

	delete[] lpStream;
	return TRUE;
}

LPCSTR CGoogleAuth::GetSID(void)
{
	if (m_strSID.empty())
		return NULL;

	return m_strSID.c_str();
}

LPCSTR CGoogleAuth::GetLSID(void)
{
	if (m_strLSID.empty())
		return NULL;

	return m_strLSID.c_str();
}

LPCSTR CGoogleAuth::GetAuth(void)
{
	if (m_strAuth.empty())
		return NULL;

	return m_strAuth.c_str();
}

}